// pages/goodsmain/goodmain.js
var Ajax = require('../../utils/Ajax.js')
var utils = require('../../utils/util.js');
var config = require('../../base.conf.js').config;
var app = getApp();
var timer = null;
var isbtn=true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    islook: false,//是否查询了可兑换
    showModel: false,
    productId: '',
    onlineType: 4,
    plProductFirstStep: '',
    iserror: false,
    getUserStep: '',
    statuserro: false,
    statusType: 'none',
    weChatInfo: '',
    isExchange: true, //查询是否能兑换
    noEnoughType: 1, //1:步数不够 3:其他情况
    isExchangeTip: '', //不能兑换的提示语
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (wx.hideShareMenu) { //关闭右上角分享
      wx.hideShareMenu();
    }
    options.ischang = options.ischang == 0 ? options.ischang:1;
    this.setData({
      options,
      onlineType: options.onlineType||4,
      productId: options.productId || '',
    })
  },
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      weChatInfo: utils.getWechatInfo(),
      getUserStep: utils.getUserStep()
    }, () => {
      utils.showLoading();
      this.getProductDetail()
    })
  },
  upDatastepUi() {
    this.setData({
      weChatInfo: utils.getWechatInfo(),
      getUserStep: utils.getUserStep()
    })
  },
  //没有UID弹窗
  showModal(id) {
    var modal = this.selectComponent("#" + (id || 'isExchange'));
    modal.show();
  },
  closeModal(e) { //关闭弹窗
    var id = this.onSetid(e);
    var modal = this.selectComponent("#" + (id || 'isExchange'));
    modal.hide();
  },
  onSetid(e) { //弹出窗的ID获取
    var id = 'modal'
    if (typeof(e) == 'string') {
      id = e
    } else {
      id = e && (e.currentTarget.id || e.currentTarget.dataset.id);
    }
    return id;
  },
  //查询商品详情
  getProductDetail() {
    var {
      productId,
      onlineType,
      onlineType
    } = this.data;
    var data = {
      productId: productId,
      type: onlineType
    }
    Ajax.get("productDetail", data, null, true).then((d) => {
      wx.stopPullDownRefresh();
      if (d.status == 200 && d.code == 0) {
        if (d.code == 0 && !d.data) {
          this.setData({
            statuserro: false,
            statusType: 'empty',
          })
          return;
        }
        clearInterval(timer);
        d.data.iffDate = d.data.iffDate > 0 ? d.data.iffDate : null;
        if (d.data && !d.data.iffday && d.data.iffDate && d.data.isExchange == 0) {
          d.data.timesArr = d.data.iffDate && this.dateDif(d.data.iffDate);
        }
        // d.data.stock = 0;
        this.setData({
          plProductFirstStep: d.data,
          statuserro: false,
          statusType: 'none',
        }, () => {
          var { onlineType, options, plProductFirstStep } = this.data;
          if (onlineType==4){
            options.ischang = plProductFirstStep.integral > 0 ? 1 : 0;
            this.setData({
              options
            }, () => {
              if (plProductFirstStep.integral){
                this.isExchangeFn();
              }else{
                this.setData({
                  islook: true
                }, () => {
                  utils.hideLoading()
                })
              }
            })
          }else{
             this.setData({
               islook:true
             },()=>{
               utils.hideLoading()
             })
          }
          if (this.data.plProductFirstStep.isExchange == 0) {
            return;
          }
          timer = setInterval(() => {
            var {
              plProductFirstStep: {
                iffDate,
                iffday
              }
            } = this.data;
            if (!iffday && iffDate) {
              this.setData({
                ['plProductFirstStep.timesArr']: this.dateDif(iffDate),
                ['plProductFirstStep.iffDate']: Number(iffDate) - 1000 > 0 ? Number(iffDate) - 1000 : 0
              })
            } else {
              clearInterval(timer);
              this.setData({
                ['plProductFirstStep.iffDate']: iffDate > 0 ? iffDate : 0
              })
            }
          }, 1000)
        })
      } else {
        var {
          plProductFirstStep
        } = this.data;
        this.setData({
          statuserro: false,
          statusType: plProductFirstStep ? "none" : 'empty',
        })
        utils.showtoast(d.data || d.msg || d.message || "内部服务器错误")
      }
    }).catch((e) => {
      wx.stopPullDownRefresh();
      utils.hideLoading();
      var {
        plProductFirstStep
      } = this.data;
      this.setData({
        statuserro: false,
        statusType: plProductFirstStep ? "none" : 'empty',
      })
      utils.showtoast('网络加载失败，刷新重试')
    })
  },
  dateDif(date) { //处理倒计时
    if (date <= 0) {
      return null;
    }
    var days = date / 1000 / 60 / 60 / 24;
    var daysRound = Math.floor(days); //对一个数进行下舍入。
    var hours = date / 1000 / 60 / 60 - (24 * daysRound);
    var hoursRound = Math.floor(hours);
    var minutes = date / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
    var minutesRound = Math.floor(minutes);
    var seconds = date / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
    var secondsRound = Math.floor(seconds);
    return [this.addZero(daysRound), this.addZero(hoursRound), this.addZero(minutesRound), this.addZero(secondsRound)];
  },
  addZero(numbers) { //小于10前面加一个零
    if (numbers < 10) {
      return "0" + numbers
    }
    return numbers;
  },
  //进入页面查询是否能兑换
  isExchangeFn() {
    var { onlineType, options } = this.data;
    if (onlineType == 2){
      this.setData({
        islook: true
      })
      utils.hideLoading();
      return;
    }
    if (options.ischang==0){
      utils.hideLoading();
      this.setData({
        islook: true
      })
      return;
    }
    var {
      getUserStep,
      productId,
      onlineType
    } = this.data;
    Ajax.post('doExchange', {
      uuid: getUserStep && getUserStep.uuid,
      productId: productId,
      type: onlineType,
    }).then((d) => {
      if (d.status == 200 && d.code == 0) {
        //跳转小程序
        this.setData({
          isExchange: true,
        })
      } else if (d.status == 200 && d.code == 40009) {
        this.setData({
          noEnoughType: 1,
          isExchange: false,
        })
      } else {
        this.setData({
          noEnoughType: 2,
          isExchange: false,
          isExchangeTip: d.msg
        })
      }
      setTimeout(()=>{
        utils.hideLoading();
      },500)
      this.setData({
        islook: true
      })
    }).catch((e) => {
      console.log(e)
      this.setData({
        islook:true
      })
      utils.hideLoading()
      utils.showtoast('网络加载失败，刷新重试')
    })
  },
  //可以兑换
  sendbtn(e) {
    if (!isbtn){
      return;
    }
    isbtn=false;
    var { onlineType}=this.data;
    var shareId = app.getValueSync("shareId") || app.globalData.channelInfo.shareId || ''
    if (shareId == this.data.getUserStep.shareId) {
      shareId = ''
    }
    // var url = 'pages/goodsmain/goodsmain?productId=' + this.data.productId + '&onlineType=' + this.data.onlineType + '&shareId=' + shareId
    // if (onlineType==4){
      var url='pages/goodsmain/goodsmain?productId=' + this.data.productId + '&onlineType=' + this.data.onlineType + '&action=neighbor' + '&shareId=' + shareId
    // }
    console.log(url)
    wx.navigateToMiniProgram({
      appId: 'wx8407e4c0b132614a',
      path: url,
      envVersion: config.isDebug ? 'trial' : 'release',
      success(res) {
        isbtn = true;
      },
      fail(res) {
        isbtn = true;
        console.log(res)
      }
    })
  },
  //不可以兑换
  nosendbtn() {
    if (this.data.noEnoughType == 2) {
      utils.showtoast(this.data.isExchangeTip || '未知异常')
    } else {
      this.showModal();
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.getProductDetail();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    this.closeModal('isExchange');
    var {
      weChatInfo,
      plProductFirstStep,
      getUserStep
    } = this.data;
    return {
      title: `${weChatInfo.userInfo.nickName}发起了捐赠步数换礼物，快来帮TA！`,
      path: `/pages/sponsorship/sponsorship?uuid=${getUserStep && getUserStep.uuid || ''}&shareId=${getUserStep&&getUserStep.shareId || ''}`,
      imageUrl: '../../assets/img/step.png',
    }
  }
})